
package view;

import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JLabel;
import model.Ant;
import model.Space2D;

public class RunThread extends Thread{
	
	Grid grid;
	Space2D universe;
	boolean isRunning;
	int tsleep;
	int nbStep;
	int vanishTime;
	JLabel nbStepPanel;
	JLabel r1Label;
	JLabel r2Label;
	JLabel r3Label;
	
	public RunThread(Grid grid, Space2D universe, int tsleep, int nbStep, JLabel nbStepPanel, JLabel r1Label,JLabel r2Label,JLabel r3Label, int vanishTime){
		super();
		this.grid = grid;
		this.universe = universe;
		isRunning = true;
		this.tsleep = tsleep;
		this.nbStep = nbStep;
		this.nbStepPanel = nbStepPanel;
		this.r1Label = r1Label;
		this.r2Label = r2Label;
		this.r3Label = r3Label;
		this.vanishTime = vanishTime;
	}
	
	public void setTSleep(int tsleep){
		this.tsleep = tsleep;
	}
	
	public void run(){
		int size = universe.getListAnts().size();
		
		while(true && isRunning){
			int r1Found = 0;
			int r2Found = 0;
			int r3Found = 0;
			for (int i = 0; i<size;i++){
				if (this.vanishTime != 0){
					if (this.nbStep%this.vanishTime==0){
						this.universe.decPheromones();
					}
				}
				Ant ant = universe.getListAnts().get(i);
				try {
					ant.step();
				} catch (Exception ex) {
					Logger.getLogger(RunThread.class.getName()).log(Level.SEVERE, null, ex);
				}
			}
			this.nbStep++;
			
			ArrayList<Ant> ants = this.universe.getListAnts();
			
			for (int i = 0; i<size;i++){
				Ant ant = ants.get(i);
				r1Found += ant.getR1Found();
				r2Found += ant.getR2Found();
				r3Found += ant.getR3Found();
			}
			
			if (this.tsleep>=0){
			
				grid.repaint();
				this.nbStepPanel.setText("Nombre d'etapes : "+this.nbStep);
				this.nbStepPanel.repaint();
				this.r1Label.setText(""+r1Found);
				this.r2Label.setText(""+r2Found);
				this.r3Label.setText(""+r3Found);
				this.r1Label.repaint();
				this.r2Label.repaint();
				this.r3Label.repaint();
				try {
					Thread.sleep(tsleep);
				} catch (InterruptedException ex) {
					Logger.getLogger(RunThread.class.getName()).log(Level.SEVERE, null, ex);
				}
			} else {
				if (nbStep%(-tsleep) == 0){
					grid.repaint();
					this.nbStepPanel.setText("Nombre d'etapes : "+this.nbStep);
					this.nbStepPanel.repaint();
					this.r1Label.setText(""+r1Found);
					this.r2Label.setText(""+r2Found);
					this.r3Label.setText(""+r3Found);
					this.r1Label.repaint();
					this.r2Label.repaint();
					this.r3Label.repaint();
				}
			}
		}
	}
	
	public int kill(){
		isRunning = false;
		return this.nbStep;
	}

	public int getVanishTime() {
		return vanishTime;
	}

	public void setVanishTime(int vanishTime) {
		this.vanishTime = vanishTime;
	}	
}
